<template>
  <div class="customer-list-container">
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <el-form :inline="true" :model="searchForm" class="demo-form-inline">
            <el-form-item label="客户名称">
              <el-input
                v-model="searchForm.name"
                placeholder="请输入客户名称"
              />
            </el-form-item>
            <el-form-item label="联系电话">
              <el-input
                v-model="searchForm.phone"
                placeholder="请输入联系电话"
              />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="handleSearch">搜索</el-button>
              <el-button @click="resetSearch">重置</el-button>
            </el-form-item>
          </el-form>
          <el-button type="primary" @click="handleAdd">新增客户</el-button>
        </div>
      </template>

      <el-table
        :data="filteredCustomers"
        style="width: 100%"
        @sort-change="handleSortChange"
      >
        <el-table-column prop="id" label="ID" width="80" sortable="custom" />
        <el-table-column
          prop="name"
          label="客户名称"
          width="120"
          sortable="custom"
        />
        <el-table-column
          prop="phone"
          label="联系电话"
          width="120"
          sortable="custom"
        />
        <el-table-column
          prop="email"
          label="电子邮箱"
          width="180"
          sortable="custom"
        />
        <el-table-column
          prop="address"
          label="地址"
          width="200"
          sortable="custom"
        />
        <el-table-column
          prop="createdAt"
          label="创建时间"
          width="180"
          sortable="custom"
        />
        <el-table-column label="操作" width="180">
          <template #default="scope">
            <el-button size="small" @click="handleEdit(scope.row)"
              >编辑</el-button
            >
            <el-button
              size="small"
              type="danger"
              @click="handleDelete(scope.row)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="totalCustomers"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 新增/编辑客户对话框 -->
    <el-dialog v-model="dialogVisible" :title="dialogTitle" width="40%">
      <el-form :model="customerForm" label-width="100px">
        <el-form-item label="客户名称">
          <el-input v-model="customerForm.name" />
        </el-form-item>
        <el-form-item label="联系电话">
          <el-input v-model="customerForm.phone" />
        </el-form-item>
        <el-form-item label="电子邮箱">
          <el-input v-model="customerForm.email" />
        </el-form-item>
        <el-form-item label="地址">
          <el-input v-model="customerForm.address" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSaveCustomer">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";

// 模拟客户数据
const customers = ref([
  {
    id: 1,
    name: "张三",
    phone: "13800138000",
    email: "zhangsan@example.com",
    address: "北京市朝阳区",
    createdAt: "2023-01-01",
  },
  {
    id: 2,
    name: "李四",
    phone: "13900139000",
    email: "lisi@example.com",
    address: "上海市浦东新区",
    createdAt: "2023-01-02",
  },
  {
    id: 3,
    name: "王五",
    phone: "13700137000",
    email: "wangwu@example.com",
    address: "广州市天河区",
    createdAt: "2023-01-03",
  },
  {
    id: 4,
    name: "赵六",
    phone: "13600136000",
    email: "zhaoliu@example.com",
    address: "深圳市南山区",
    createdAt: "2023-01-04",
  },
  {
    id: 5,
    name: "钱七",
    phone: "13500135000",
    email: "qianqi@example.com",
    address: "杭州市西湖区",
    createdAt: "2023-01-05",
  },
]);

const searchForm = ref({
  name: "",
  phone: "",
});

const currentPage = ref(1);
const pageSize = ref(10);
const totalCustomers = ref(0);

const sortBy = ref("");
const sortOrder = ref("ascending");

const dialogVisible = ref(false);
const dialogTitle = ref("");
const customerForm = ref({
  id: null,
  name: "",
  phone: "",
  email: "",
  address: "",
});

// 过滤和排序后的客户列表
const filteredCustomers = computed(() => {
  let result = customers.value.filter(
    (customer) =>
      customer.name
        .toLowerCase()
        .includes(searchForm.value.name.toLowerCase()) &&
      customer.phone.includes(searchForm.value.phone)
  );

  if (sortBy.value) {
    result.sort((a, b) => {
      if (a[sortBy.value] < b[sortBy.value])
        return sortOrder.value === "ascending" ? -1 : 1;
      if (a[sortBy.value] > b[sortBy.value])
        return sortOrder.value === "ascending" ? 1 : -1;
      return 0;
    });
  }

  totalCustomers.value = result.length;
  return result.slice(
    (currentPage.value - 1) * pageSize.value,
    currentPage.value * pageSize.value
  );
});

// 搜索处理
const handleSearch = () => {
  currentPage.value = 1;
};

// 重置搜索
const resetSearch = () => {
  searchForm.value = {
    name: "",
    phone: "",
  };
  handleSearch();
};

// 排序处理
const handleSortChange = ({ prop, order }) => {
  sortBy.value = prop;
  sortOrder.value = order;
};

// 分页处理
const handleSizeChange = (val) => {
  pageSize.value = val;
  currentPage.value = 1;
};

const handleCurrentChange = (val) => {
  currentPage.value = val;
};

// 新增客户
const handleAdd = () => {
  dialogTitle.value = "新增客户";
  customerForm.value = {
    id: null,
    name: "",
    phone: "",
    email: "",
    address: "",
  };
  dialogVisible.value = true;
};

// 编辑客户
const handleEdit = (row) => {
  dialogTitle.value = "编辑客户";
  customerForm.value = { ...row };
  dialogVisible.value = true;
};

// 删除客户
const handleDelete = (row) => {
  ElMessageBox.confirm("确定要删除该客户吗？", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      customers.value = customers.value.filter(
        (customer) => customer.id !== row.id
      );
      ElMessage({
        type: "success",
        message: "删除成功",
      });
    })
    .catch(() => {
      // 取消删除
    });
};

// 保存客户（新增或编辑）
const handleSaveCustomer = () => {
  if (customerForm.value.id) {
    // 编辑现有客户
    const index = customers.value.findIndex(
      (customer) => customer.id === customerForm.value.id
    );
    if (index !== -1) {
      customers.value[index] = { ...customerForm.value };
    }
  } else {
    // 新增客户
    const newCustomer = {
      ...customerForm.value,
      id: customers.value.length + 1,
      createdAt: new Date().toISOString().split("T")[0],
    };
    customers.value.push(newCustomer);
  }
  dialogVisible.value = false;
  ElMessage({
    type: "success",
    message: customerForm.value.id ? "编辑成功" : "新增成功",
  });
};

onMounted(() => {
  // 在实际应用中，这里可能会从API获取客户数据
  totalCustomers.value = customers.value.length;
});
</script>

<style scoped>
.customer-list-container {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.pagination-container {
  margin-top: 20px;
  text-align: right;
}
</style>
